package com.ybear.ybcomponent.base.adapter.layoutcache

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.view.ContextThemeWrapper
import androidx.asynclayoutinflater.view.AsyncLayoutInflater

/**
 * @Author MiWi
 * @Date 2024年1月24日
 * @Description 布局优化-核心类
 */
class LayoutInflaterOptimize internal constructor() : ILayoutInflater {
    private var mInflater: AsyncLayoutInflater? = null
    private val mViewCache: ViewCache = ViewCache()

    companion object {
        @JvmStatic
        private val i by lazy { LayoutInflaterOptimize() }
        @JvmStatic
        fun get(): LayoutInflaterOptimize { return i }
    }

    override fun asyncInflateView(parent: ViewGroup, layoutId: Int, callback: InflateCallback?) {
        if (mInflater == null) {
            val context = parent.context
            mInflater = AsyncLayoutInflater(
                ContextThemeWrapper(
                    context.applicationContext, context.theme
                )
            )
        }
        mInflater?.inflate( layoutId, parent ) {
            view: View?, resId: Int, _: ViewGroup? -> callback?.onInflateFinished( resId, view )
        }
    }

    override fun inflateView(parent: ViewGroup, layoutId: Int): View? {
        return LayoutInflater.from( parent.context ).inflate( layoutId, parent, false )
    }

    fun getView(layoutId: Int): View? {
        return mViewCache.getView(layoutId)
    }

    fun preload(parent: ViewGroup, layoutId: Int, maxCount: Int) {
        val viewsAvailableCount = mViewCache.getViewPoolAvailableCount(layoutId)
        if (viewsAvailableCount >= maxCount) {
            return
        }
        for (i in 0 until maxCount - viewsAvailableCount) {
            // 异步加载View
            asyncInflateView(parent, layoutId, object : InflateCallback {
                override fun onInflateFinished(layoutId: Int, view: View?) {
                    mViewCache.putView(layoutId, view)
                }
            })
        }
    }
}